<template>
  <el-dialog :model-value="true" title="公式" width="600px" align-center destroy-on-close @close="handleClose">
    <el-form @submit.prevent>
      <el-form-item>
        <el-input v-model="formModel.value" :rows="6" placeholder="请输入内容，支持Latex公式" type="textarea" />
      </el-form-item>
      <el-form-item label="预览：">
        <div id="formula" style="min-height: 50px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose()">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
  import { nextTick, onMounted, reactive, watch } from 'vue'
  import 'katex/dist/katex.min.css'
  import { katexRender } from '@/utils/base.js'

  const props = defineProps({
    value: {
      type: String,
      default: ''
    },
    insert: {
      type: Boolean,
      default: true
    }
  })

  // 表单
  const formDefault = {
    value: props.value,
    insert: props.insert
  }
  const formModel = reactive({ ...formDefault })

  // 初次挂载时渲染公式
  onMounted(() => {
    nextTick(() => {
      katexRender(formModel.value, document.getElementById('formula'))
    })
  })

  // 监听 formModel.value 变化，重新渲染公式
  watch(
    () => formModel.value,
    (newVal) => {
      if (newVal !== undefined) {
        katexRender(formModel.value, document.getElementById('formula'))
      }
    }
  )

  const emit = defineEmits(['close'])
  // 关闭
  const handleClose = () => {
    emit('close')
  }
  const handleSubmit = () => {
    emit('close', formModel)
  }
</script>
